<?php

/*
 * Custom router function v 0.1
 *
 * Add functionality : read into more than one sub-folder
 *
 */

class MY_Router extends CI_Router
{

	function __construct()
	{
		parent::__construct();
		log_message('debug', "MY_Router Class Initialized");
	}

	/**
	 * Validates the supplied segments.  Attempts to determine the path to
	 * the controller.
	 *
	 * @access	private
	 * @param	array
	 * @return	array
	 */
	function _validate_request($segments)
	{
		if (count($segments) == 0)
		{
			return $segments;
		}

		// Does the requested controller exist in the root folder?
		if (file_exists(APPPATH.'controllers/'.$this->directory.$segments[0].'.php'))
		{
			log_message('debug', $this->directory.$segments[0].' is a controller.');
			return $segments;
		} else {
			log_message('debug', $this->directory.$segments[0].' is NOT a controller.');
		}

		// Is the controller in a sub-folder?
		if (is_dir(APPPATH.'controllers/'.$this->directory.$segments[0]))
		{
			log_message('debug', $this->directory.$segments[0].' is a sub-folder.');
			// Set the directory and remove it from the segment array
			$this->set_directory($segments[0],$this->directory);
			$segments = array_slice($segments, 1);

			return $this->_validate_request($segments);
		} else {
			log_message('debug', $this->directory.$segments[0].' is NOT a sub-folder.');
		}


		// If we've gotten this far it means that the URI does not correlate to a valid
		// controller class.  We will now see if there is an override
		if ( ! empty($this->routes['404_override']))
		{
			$x = explode('/', $this->routes['404_override']);

			$this->set_class($x[0]);
			$this->set_method(isset($x[1]) ? $x[1] : 'index');

			return $x;
		}


		// Nothing else to do at this point but show a 404
		show_404($segments[0]);
	}

	/**
	 *  Set the directory name
	 *
	 * @access	public
	 * @param	string
	 * @return	void
	 */
	function set_directory($dir, $base='')
	{
		$this->directory = $base.str_replace(array('/', '.'), '', $dir).'/';
	}
}


